var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
const fs = require('fs');
const path = require('path');
const guangModel = require('../../database/guang');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 获取所有广告
router.get('/ads', async function(req, res) {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const skip = (page - 1) * pageSize;
    const sortField = req.query.sortField || 'createTime';
    const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1;
    const status = req.query.status || null;
    
    // 检查并更新过期的广告
    const today = new Date().toISOString().split('T')[0];
    await guangModel.updateMany(
      { 
        status: { $ne: '已结束' }, 
        endDate: { $lt: today } 
      },
      { $set: { status: '已结束' } }
    );
    
    // 构建查询条件
    const query = {};
    if (status) {
      query.status = status;
    }
    
    // 计算总数
    const total = await guangModel.countDocuments(query);
    
    // 分页查询
    const sort = {};
    sort[sortField] = sortOrder;
    
    const ads = await guangModel.find(query, {
      title: 1,
      type: 1,
      status: 1,
      startDate: 1,
      endDate: 1,
      views: 1,
      clicks: 1,
      link: 1,
      createTime: 1
    })
    .sort(sort)
    .skip(skip)
    .limit(pageSize)
    .lean(); // 使用lean()获取纯JavaScript对象，提高性能

    console.log(ads);
    
    
    res.json({
      code: 200,
      message: '获取广告列表成功',
      data: {
        items: ads,
        total,
        page,
        pageSize
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取广告列表失败',
      error: error.message
    });
  }
});

// 根据ID获取单个广告
router.get('/ads/:id', async function(req, res) {
  try {
    const ad = await guangModel.findById(req.params.id);

    // 自动更新状态
  const now = new Date();
  for (const ad of ads) {
    if (new Date(ad.endDate) < now && ad.status !== '已结束') {
      console.log(ad);
      
      ad.status = '已结束';
      await ad.save();
    }
  }

    if (!ad) {
      return res.status(404).json({
        code: 404,
        message: '广告不存在'
      });
    }
    res.json({
      code: 200,
      message: '获取广告成功',
      data: ad
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取广告失败',
      error: error.message
    });
  }
});

// 创建广告
router.post('/ads', async function(req, res) {
  try {
    const newAd = new guangModel(req.body);
    const savedAd = await newAd.save();
    res.status(201).json({
      code: 201,
      message: '创建广告成功',
      data: savedAd
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '创建广告失败',
      error: error.message
    });
  }
});

// 更新广告
router.put('/ads/:id', async function(req, res) {
  try {
    const updatedAd = await guangModel.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );
    if (!updatedAd) {
      return res.status(404).json({
        code: 404,
        message: '广告不存在'
      });
    }
    res.json({
      code: 200,
      message: '更新广告成功',
      data: updatedAd
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '更新广告失败',
      error: error.message
    });
  }
});

// 删除广告
router.delete('/ads/:id', async function(req, res) {
  try {
    const deletedAd = await guangModel.findByIdAndDelete(req.params.id);
    if (!deletedAd) {
      return res.status(404).json({
        code: 404,
        message: '广告不存在'
      });
    }
    res.json({
      code: 200,
      message: '删除广告成功',
      data: deletedAd
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '删除广告失败',
      error: error.message
    });
  }
});

// 更新广告状态
router.patch('/ads/:id/status', async function(req, res) {
  try {
    const { status } = req.body;
    const updatedAd = await guangModel.findByIdAndUpdate(
      req.params.id,
      { status },
      { new: true }
    );
    if (!updatedAd) {
      return res.status(404).json({
        code: 404,
        message: '广告不存在'
      });
    }
    res.json({
      code: 200,
      message: '更新广告状态成功',
      data: updatedAd
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '更新广告状态失败',
      error: error.message
    });
  }
});

module.exports = router;